package edu.must.uh.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class ToolsOfDate {  

        
        public static String getCurrDate() throws Exception {           
        	String reString = toYYYYMMDD(new Date());
            return reString;
        }
        
        
        public static String getCurrDateTime() throws Exception {
            String reString ="";
            Date d = new Date(); 
            reString = toYYYYMMDDHHMISS(new Date());
            return reString;
        }
        
      //獲取月份中的最大天數
        public static int getDaysOfMonth(int year,int month) {
            int dayCount = 0;
            Calendar cl=Calendar.getInstance();
            cl.set(Calendar.YEAR,year);
            cl.set(Calendar.MONTH,month - 1);
            dayCount=cl.getActualMaximum(Calendar.DATE);
            return dayCount;
        }
        
      
        public static Date longToDate(Object odate){   
            if(odate == null) {
                return null;
            }
            Long  dateLong = (Long) odate;
            Date date = new Date(dateLong);
            return date;
        }

        
        public static Timestamp trimTime(Timestamp ts) {
            return getDate(ts.toString().split(" ")[0]);
        }
        
        /**
         * 根据日期 找到对应日期的 星期
         */
        public static String getDayOfWeekByDate(String date,String dateForma) {
            String dayOfweek = "-1";
            try {
                SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
                Date myDate = myFormatter.parse(date);
                SimpleDateFormat formatter = new SimpleDateFormat(dateForma);
                String str = formatter.format(myDate);
                dayOfweek = str;
                
            } catch (Exception e) {
                System.out.println("错误!");
            }
            return dayOfweek;
        }
        
        public static Timestamp StringToTimestamp(String dateStr, String format) {
            Timestamp ts = null;

            String splitKey = "[ .\\/:-]";
            String stdDateStr = "YYYY-MM-DD HH:MI:SS.FF";

            if((dateStr == null || "".equals(dateStr)) || (format == null || "".equals(format))) {
                return ts;
            }
            if(!dateStr.matches("^[0-9 .\\/:-]+$")) {
                return ts;
            }
            format = format.toUpperCase();
            String[] formatOrd = format.split(splitKey);
            String[] dateStrItem = dateStr.split(splitKey);
            String[] formatItem = stdDateStr.split(splitKey);
            if(formatOrd.length != dateStrItem.length) {
                return ts;
            }
            for(int i = 0; i < formatOrd.length; i++) {
                for(int j = 0; j < formatItem.length; j++) {
                    if(formatOrd[i].equals(formatItem[j])) {
                        stdDateStr = stdDateStr.replaceFirst(formatItem[j], dateStrItem[i]);
                    }
                }
            }
            for(int i = 0; i < formatItem.length; i++) {
                stdDateStr = stdDateStr.replaceFirst(formatItem[i], "0");
            }
            ts = Timestamp.valueOf(stdDateStr);
            return ts;
        }
        
        public static Timestamp getDate(String ds) {
            if(ds == null)
                return null;

            return Timestamp.valueOf(ds.concat(" 00:00:00.0"));
        }
        
        public static Timestamp StringToTimestamp(String dateStr) {
            Timestamp ts = new Timestamp(System.currentTimeMillis());

            if(dateStr == null ) {
                return ts;
            }
            if(!dateStr.matches("^[0-9 .\\/:-]+$")) {
                return ts;
            }
            try {  
                ts = Timestamp.valueOf(dateStr); 
            } catch (Exception e) {  
                e.printStackTrace();  
            } 
            return ts;
        }
        
        public static String toYYYYMMDD(Date date) {
            String str = "";
            try{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                if(date != null){
                    str = format.format(date);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return str;
        }
        
        public static String toYYYYMMDDType(Date date) {
            String str = "";
            try{
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                if(date != null){
                    str = format.format(date);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return str;
        }
        
        public static String toYYYYMMDDHHMISS(Date date) {
            String str = "";
            try{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(date != null){
                    str = format.format(date);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return str;
        }
        
        public static String toHHMI(Date date) {
            String str = "";
            try{
                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                if(date != null){
                    str = format.format(date);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return str;
        }
        
        public static String toYYYYMMDDHHMI(Date date) {
            String str = "";
            try{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                if(date != null){
                    str = format.format(date);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return str;
        }
        
        public static int getAge(Timestamp birthday, Timestamp now){
            int age = 0;
            try{
                if(birthday != null){
                    int birthYear = birthday.getYear();
                    int birthMonth = birthday.getMonth();
                    int birthDay = birthday.getDate();
                    int nowYear = now.getYear();
                    int nowMonth = now.getMonth();
                    int nowDay = now.getDay();
                    if(birthYear < nowYear){
                        age = nowYear - birthYear;
                        if(nowMonth <= birthMonth){
                            if(nowMonth == birthMonth){
                                if(nowDay < birthDay){
                                    age--;
                                }
                            }else{
                                age--;
                            }
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return age;
        }
        
        public static String getAgeByBirth(Timestamp birthday, Timestamp now){
            int age = 0;
            String ageString= "";
            int ageYearString= 0;
            int ageMonthString= 0;
            try{
                if(birthday != null){
                    int birthYear = birthday.getYear();
                    int birthMonth = birthday.getMonth();
            
                    int nowYear = now.getYear();
                    int nowMonth = now.getMonth();                
                    if(birthMonth < nowMonth){
                        ageYearString = nowYear-birthYear;
                        ageMonthString= nowMonth-birthMonth;
                        
                    }else if(birthMonth == nowMonth){
                        ageYearString =nowYear-birthYear;
                       
                    }else {
                        ageYearString = nowYear-birthYear-1;
                        ageMonthString= nowMonth-birthMonth+12;
                    }
                    
                    if(ageYearString <=0)
                    {
                        ageString = Integer.toString(ageMonthString) +"月";
                    }else {
                        ageString = Integer.toString(ageYearString) +"歲";
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return ageString ;
        }
        
        public static int getAge(String strDay, Timestamp now){
            int age = 0;
            Timestamp birthday =StringToTimestamp(strDay);
            try{
                int birthYear = birthday.getYear();
                int birthMonth = birthday.getMonth();
                int birthDay = birthday.getDate();
                int nowYear = now.getYear();
                int nowMonth = now.getMonth();
                int nowDay = now.getDay();
                if(birthYear < nowYear){
                    age = nowYear - birthYear;
                    if(nowMonth <= birthMonth){
                        if(nowMonth == birthMonth){
                            if(nowDay < birthDay){
                                age--;
                            }
                        }else{
                            age--;
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return age;
        }

        public static String getNowDateAddDays(String currDate,int days){
            Timestamp da = StringToTimestamp(currDate,"yyyy-MM-dd");
            if(currDate != null){
                Calendar cal = Calendar.getInstance();
                cal.setTime(da);
                cal.add(Calendar.DATE, days);
                return toYYYYMMDD(cal.getTime());
            }else{
                return null;
            }
        }
        
        public static int getDaysBetweenDatesString(String first, String second, String dateFormat) {
            Date d1 = StringToTimestamp(first,dateFormat);
            Date d2 = StringToTimestamp(second,dateFormat);

            Long mils = (d2.getTime() - d1.getTime()) / (86400000);

            return mils.intValue();
        }
        
        public static int getDaysBetweenDates(Timestamp first, Timestamp second) {
            if(first != null && second != null){
                Long mils = (second.getTime() - first.getTime()) / (86400000);
                return mils.intValue();
            }else{
                return 0;
            }
        }
        
        public static List<String> getDatesBetweenTwoDates(String date1, String date2, String dateFomat){
            List<String> dateList = new ArrayList<String>();
            Date d1 = getFormatDateTime(date1, dateFomat);
            Date d2 = getFormatDateTime(date2, dateFomat);
            if(d1 == null || d2 == null){
                return null;
            }
            if(d1.compareTo(d2)==0){
                dateList.add(date1);
                return dateList;
            }
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(d1);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(d2);
            dateList.add(date1);
            while (true) {
                calendar1.add(Calendar.DAY_OF_MONTH, 1);
                SimpleDateFormat df = new SimpleDateFormat(dateFomat);
                if (calendar1.getTimeInMillis() < calendar2.getTimeInMillis()) {
                    dateList.add(df.format(calendar1.getTime()));
                } else {
                    break;
                }
            }
            dateList.add(date2);
            return dateList;
        }
        
        public static Date getFormatDateTime(String currDate, String format) {
            if (currDate == null) {
                return null;
            }
            SimpleDateFormat dtFormatdB = null;
            try {
                dtFormatdB = new SimpleDateFormat(format);
                return dtFormatdB.parse(currDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        
        public static String getCurrLastFirstMonthDate(){
            Date d = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.add(Calendar.MONTH, -1);
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String lastThreeMonth = sf.format(cal.getTime());
            return lastThreeMonth;
        }
        
        public static String getCurrFirstMonthDate(){
            Date d = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
           
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-01");
            String lastThreeMonth = sf.format(cal.getTime());
            return lastThreeMonth;
        }
        
        public static boolean isValidDate(String str, String formatStr) {
            boolean convertSuccess = true;
            if(str == null || "".equals(str)){
                return false;
            }
            // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            try {
                // 设置lenient为false.
                // 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                format.setLenient(false);
                format.parse(str);
            } catch (ParseException e) {
                // e.printStackTrace();
                // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
                convertSuccess = false;
            }
            return convertSuccess;
        }
}
